package com.softeem.sss.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.softeem.sss.dto.DownRecord;
import com.softeem.sss.dto.FileInfo;
import com.softeem.sss.utils.DBUtils;

/**
 * 1.添加记录
 * 2.查询指定id用户下载的文件记录
 * @author mrchai
 *
 */
public class DownRecordDAO {

	/**
	 * 添加一条下载记录 UUID
	 * @param dr
	 * @return
	 */
	public boolean insert(DownRecord dr){
		String sql = "insert into tb_record(rid,downloadtime,uid,fid) values(?,now(),?,?)";
		return DBUtils.exeUpdate(sql, dr.getRid(),dr.getUid(),dr.getFid());
	}
	
	/**
	 * 根据用户id查询用户的下载记录
	 * @param uid
	 * @return
	 */
	public List<FileInfo> findByUid(int uid){
		String sql = "select f.*,r.downloadtime from tb_record r,tb_files f where f.fid=r.fid and r.uid=? and r.isDel=0";
		List<FileInfo> files = new ArrayList<>();
		ResultSet rs = null;
		FileInfo file = null;
		try {
			rs = DBUtils.exeQuery(sql, uid);
			while(rs.next()){
				int fid = rs.getInt("fid");
				String fname = rs.getString("fname");
				String summary = rs.getString("summary");
				Timestamp utime = rs.getTimestamp("uploadtime");
				long size = rs.getLong("fsize");
				String md5 = rs.getString("md5");
				String path = rs.getString("path");
				String tags = rs.getString("tags");
				int dcount = rs.getInt("dcount");
				int saleIntegral = rs.getInt("saleintegral");
				int isDel = rs.getInt("isDel");
				Timestamp dtime = rs.getTimestamp("downloadtime");
				
				file = new FileInfo(fid, fname, summary, size, tags, utime, md5, path, dcount, saleIntegral, uid, isDel);
				file.setDownloadTime(dtime);
				files.add(file);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtils.close(rs, null, null);
		}
		return files;
	}
	
	public boolean deleteByRid(int rid){
		String sql  = "delete from tb_record where rid=?";
		return DBUtils.exeUpdate(sql, rid);
	}
}
